import { View, Text, ScrollView } from "@tarojs/components";
import Taro, {
  useRouter,
  navigateTo,
  useShareAppMessage,
  usePullDownRefresh,
  stopPullDownRefresh,
} from "@tarojs/taro";
import {
  Tabs,
  Image,
  Menu,
  Divider,
  Button,
  Dialog,
} from "@nutui/nutui-react-taro";
import { PlayStart } from "@nutui/icons-react-taro";
import { useState, useEffect } from "react";
import { wxExchangeDetail, wxPurchased } from "@/api/course";
import "./index.scss";
const CourseDetail = () => {
  const { params } = useRouter();
  const [detailData, setDetailData] = useState<any>(null);
  //课程目录
  const [active, setActive] = useState<number | string>("1");
  const [title, setTitle] = useState<string>("全部章节");
  const [treeData, setTreeData] = useState<any>(null);
  const [scrollIntoView, setScrollIntoView] = useState<string>("");

  //是否购买
  const [purchased, setPurchased] = useState<boolean>(true);
  const getList = async () => {
    const result = await wxPurchased(params?.opusUid);
    setPurchased(result?.data);
    const res = await wxExchangeDetail(params?.opusUid);
    setDetailData(res?.data);
    setTreeData(res?.data?.directory);
  };

  //获取课程目录
  const getTreeData = (el: any) => {
    return (
      <>
        <View
          onClick={() => {
            // if (purchased || el?.tryout) {
            navigateTo({
              url: `/pages/profile/index?bindUid=${el?.bindUid}`,
            });
            // } else {
            //   Taro.showToast({
            //     title: "暂无试学资格",
            //     icon: "none",
            //   });
            // }
          }}
          className="flex justify-between items-center gap-4 py-[32rpx]"
        >
          <View>
            <View className="text-[26rpx]">{el.dirName}</View>
            <View className="text-[24rpx] text-black/60 mt-1">
              短文｜{el.learnerNum || 0}人学过
            </View>
          </View>
          <View className="flex-shrink-0">
            {!purchased && el.tryout ? (
              <Button type="primary" size="small">
                试学
              </Button>
            ) : (
              <PlayStart size={35} color="#673ab7" />
            )}
          </View>
        </View>
        <Divider className="!m-0 !h-[2rpx]" />
      </>
    );
  };

  const openDialog = () => {
    Dialog.open("kefu", {
      title: "扫码联系客服",
      content: (
        <View className="min-h-[200px]">
          <Image
            mode="widthFix"
            lazyLoad
            width={"100%"}
            src={
              detailData?.qrcode ||
              "https://service-oss.mofabiji.com/upload/image/20251120/ca84155776f34a558f8f822657c0d13e.jpg"
            }
            showMenuByLongpress
          />
        </View>
      ),
      footer: null,
      onCancel: () => {
        Dialog.close("kefu");
      },
    });
  };

  useEffect(() => {
    getList();
  }, []);
  useShareAppMessage(() => {
    return {
      title: "短文学习",
      path: `/pages/course-detail/index?opusUid=${params?.opusUid}`,
    };
  });
  usePullDownRefresh(async () => {
    await getList();
    stopPullDownRefresh();
  });
  return (
    <View className="bg-[#F5F5F5] h-screen box-border course-detail p-3 relative">
      <View className="flex justify-between items-center gap-2 rounded-md bg-white p-2">
        <Image
          className="!w-[200rpx] !h-[200rpx]"
          mode="aspectFit"
          src={detailData?.coverImage}
        />
        <View className="flex-1 flex flex-col font-normal">
          <View className="text-base font-semibold line-clamp-1">
            {detailData?.opusName}
          </View>
          <View className="text-sm text-gray-500 line-clamp-3 mt-2 mb-1">
            {detailData?.opusDesc}
          </View>
          <View className="flex justify-between items-center text-sm text-gray-500 mt-2">
            {detailData?.learnerNum || 0} 人次
          </View>
        </View>
      </View>
      <Tabs value={active} onChange={setActive}>
        <Tabs.TabPane title="简介" value="1" className="!bg-transparent !p-2" />
        <Tabs.TabPane title="目录" value="2" className="!bg-transparent !p-0" />
      </Tabs>
      {active === "1" && (
        <View>
          {detailData?.introduceImages?.map((item) => (
            <Image
              className="!w-full !h-auto"
              mode="widthFix"
              key={item}
              src={item}
            />
          ))}
        </View>
      )}
      {active === "2" && (
        <View className="relative">
          <View className="rounded-md bg-white flex items-center gap-4 mb-2 p-4">
            {treeData?.some((item: any) => !item?.creativeContentUid) && (
              <Menu className="w-[240rpx] h-[50rpx]">
                <Menu.Item
                  className="!w-screen ml-[-55rpx]"
                  title={title}
                  defaultValue="all"
                  options={[
                    {
                      text: <View>全部章节（共课时）</View>,
                      value: "all",
                    },
                    ...treeData
                      ?.filter((item: any) => !item?.creativeContentUid)
                      ?.map((item: any) => ({
                        text: (
                          <View>
                            {item?.dirName}（共{item?.children?.length || 0}
                            课时）
                          </View>
                        ),
                        value: item?.dirUid,
                      })),
                  ]}
                  onChange={(val) => {
                    if (val.value === "all") {
                      setTitle("全部章节");
                    } else {
                      setScrollIntoView(`section-${val.value}`);
                      const data = treeData?.find(
                        (item: any) => item?.dirUid === val.value
                      );
                      setTitle(data?.dirName);
                    }
                  }}
                />
              </Menu>
            )}
            <Text className="text-[28rpx] text-black/50">
              共
              {treeData?.reduce((total: number, item: any) => {
                return total + (item.children?.length || 0);
              }, 0) +
                treeData?.filter((item: any) => item?.creativeContentUid)
                  ?.length}
              课时
            </Text>
          </View>
          <ScrollView
            scrollY
            usingSticky
            scrollIntoView={scrollIntoView}
            className="!h-[calc(100vh-264px)] rounded-md bg-white"
          >
            <View className="min-h-[calc(100vh-264px)]">
              {treeData?.map((item, index) =>
                !item.creativeContentUid ? (
                  <View
                    id={`section-${item.dirUid}`}
                    key={item.dirUid}
                    className="m-4"
                    style={{
                      marginBottom:
                        index === treeData?.length - 1 ? "0" : "32rpx",
                    }}
                  >
                    <View className="w-full bg-white z-[10] py-2 text-[28rpx] font-semibold flex items-center gap-2 sticky top-0">
                      <View className="w-[8rpx] h-[28rpx] bg-[#673ab7]"></View>
                      {item?.dirName}
                    </View>
                    {item?.children?.length > 0 ? (
                      item?.children?.map((el: any) => (
                        <View key={el.dirUid}>{getTreeData(el)}</View>
                      ))
                    ) : (
                      <View className="text-black/50 text-[24rpx]">
                        暂无数据
                      </View>
                    )}
                  </View>
                ) : (
                  <View
                    key={item.dirUid}
                    className="m-2"
                    style={{
                      marginBottom:
                        index === treeData?.length - 1 ? "0" : "32rpx",
                    }}
                  >
                    {getTreeData(item)}
                  </View>
                )
              )}
            </View>
            {!purchased && (
              <View className="z-[10] sticky bottom-0 bg-white flex justify-between px-8 py-2 pay rounded-md">
                <Button
                  type="primary"
                  onClick={() => {
                    for (const item of treeData || []) {
                      // 如果有 creativeContentUid，直接跳转
                      if (item.creativeContentUid) {
                        Taro.navigateTo({
                          url: `/pages/profile/index?bindUid=${item.bindUid}`,
                        });
                        return;
                      }
                      // 否则查找子项
                      const tryoutLesson = item.children?.find(
                        (el: any) => el?.tryout
                      );
                      if (tryoutLesson) {
                        Taro.navigateTo({
                          url: `/pages/profile/index?bindUid=${tryoutLesson.bindUid}`,
                        });
                        return;
                      }
                    }
                    // 如果没有找到试学课程，可以提示用户
                    Taro.showToast({
                      title: "暂无试学课程",
                      icon: "none",
                    });
                  }}
                >
                  点击试学
                </Button>
                <Button
                  type="primary"
                  onClick={() => {
                    Taro.reportEvent("buy_course", {});
                    openDialog();
                  }}
                >
                  购买全课程
                </Button>
              </View>
            )}
          </ScrollView>
          {detailData?.qrcode && (
            <View
              onClick={() => {
                openDialog();
              }}
              className="absolute left-0 bottom-[50px] flex justify-center items-center !bg-white rounded-full p-2 shadow-lg"
            >
              <Image
                width={30}
                height={30}
                src={require("../../assets/course/kefu.svg")}
              />
            </View>
          )}
        </View>
      )}
      <Dialog id="kefu" />
    </View>
  );
};

export default CourseDetail;
